<template>
  <div>
    <!-- 面包屑导航 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<!-- 卡片视图 -->
<el-card>
<el-button class="addRole" type="primary" @click="addRoledialogVisible = !addRoledialogVisible">添加角色</el-button>
<!-- 角色列表区域 -->
<el-table :data="rolesList" stripe border="">
  <!-- 展开列 -->
  <el-table-column type="expand">
    <template slot-scope="scope">
      <el-row :class="['bd-bt', index1 === 0 ? 'bd-top' : '', 'veticalCenter']" v-for="(item1,index1) in scope.row.children" :key = "item1.id">
        <!-- 渲染一级权限 -->
        <el-col :span="5">
        <el-tag @close='deleteRight(scope.row,item1.id)' closable>{{ item1.authName }}</el-tag>
        <i class="el-icon-caret-right"></i>
        </el-col>
        <!-- 渲染二,三级权限 -->
        <el-col :span="19">
           <el-row :class="[ i2 === 0 ? '' :'bd-top', 'veticalCenter' ]" v-for="(item2,i2) in item1.children" :key="item2.id">
             <!-- 渲染二级权限 -->
             <el-col :span="6">
               <el-tag closable type="success" @close='deleteRight(scope.row,item2.id)'>{{ item2.authName }}</el-tag>
               <i class="el-icon-caret-right"></i>
             </el-col>
             <!-- 渲染三级权限 -->
             <el-col :span="18">
                   <el-tag type="warning" :class="[ i3 === 0 ? '' : 'bd-top'   ]"
                   v-for="(item3,i3) in item2.children" :key="item3.id" closable
                   @close='deleteRight(scope.row,item3.id)'>
                   {{item3.authName}}
                   </el-tag>
             </el-col>
           </el-row>
        </el-col>
      </el-row>
    </template>
  </el-table-column>
  <!-- 索引列 -->
  <el-table-column type="index"></el-table-column>
  <el-table-column  label="角色名称" prop="roleName"></el-table-column>
  <el-table-column  label="角色描述" prop="roleDesc"></el-table-column>
  <el-table-column  label="操作" >
    <template slot-scope="scope">
<el-button  size="mini" type="primary" icon="el-icon-edit" @click="edidRoles(scope.row.id)">编辑</el-button>
<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteRoles(scope.row.id)">删除</el-button>
 <el-tooltip class="item" effect="dark" content="权限分配" placement="top" :enterable='false'>
<el-button size="mini" type="warning" icon="el-icon-setting" @click="setRightsListDialog(scope.row)">分配权限</el-button>
 </el-tooltip>
    </template>
  </el-table-column>
</el-table>
</el-card>
<!-- 修改角色dialog对话框 -->
<el-dialog
  title="修改角色信息"
  :visible.sync="dialogVisible"
  width="30%">
  <!-- 修改角色表单 -->
  <el-form ref="edidRolesFormRef" :model="currentRoleInfo" label-width="80px">
  <el-form-item label="角色名称">
    <el-input v-model="currentRoleInfo.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述">
    <el-input v-model="currentRoleInfo.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="modifyRole">确 定</el-button>
  </span>
</el-dialog>
<!-- 添加角色对话框 -->
<el-dialog
  title="添加角色"
  :visible.sync="addRoledialogVisible"
  width="30%">
  <!-- 添加角色表单 -->
  <el-form ref="addRoleFormRef" :model="addFormInfo" label-width="80px">
  <el-form-item label="角色名称">
    <el-input v-model="addFormInfo.roleName"></el-input>
  </el-form-item>
  <el-form-item label="角色描述">
    <el-input v-model="addFormInfo.roleDesc"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addRoledialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRoles">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配权限对话框 -->
<el-dialog
  title="分配权限"
  :visible.sync="RightsListDialogVisible"
  width="50%">
  <!-- 权限管理树形空间展示 -->
  <el-tree ref="treeRef" :data="rightsList" :props="treeProps" show-checkbox node-key='id' :default-checked-keys= 'defKeys' :default-expand-all='true'></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="RightsListDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click=authorityAssignment>确 定</el-button>
  </span>
</el-dialog>
</div>
</template>
<script>
export default {
  data() {
    return {
      // 获取的角色列表数据
      rolesList: [],
      // 控制对话框的显示与隐藏
      dialogVisible: false,
      addRoledialogVisible: false,
      // 当前角色信息
      currentRoleInfo: [],
      // 添加用户的动态数据绑定
      addFormInfo: {},
      // 控制权限分配对话框的显示与隐藏
      RightsListDialogVisible: false,
      // 权限列表数据
      rightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认被选中的三级权限
      defKeys: []
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败!')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 点击编辑按钮，修改角色信息
    async edidRoles(id) {
      // 根据id 获得当前角色信息
      const { data: res } = await this.$http.get('roles/' + id)
      console.log(res)
      this.currentRoleInfo = res.data
      this.dialogVisible = true
    },
    // 点击确定按钮，发送请求
    async modifyRole() {
      const { data: res } = await this.$http.put('roles/' + this.currentRoleInfo.roleId, {
        roleName: this.currentRoleInfo.roleName,
        roleDesc: this.currentRoleInfo.roleDesc
      })
      if (res.meta.status !== 200) return this.$message.error('角色修改失败！')
      this.$message.success('角色修改成功！')
      // console.log(res)
      // 重新获取角色列表
      this.getRolesList()
      this.dialogVisible = false
    },
    // 根据id删除用户
    async deleteRoles(id) {
      // 删除前给用户一个确认，防止误删
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => { return err })
      // console.log(result)
      // 点击确认返回confirm
      // 点击确认返回cancel
      if (result === 'confirm') {
        // 发送请求调用后台接口，删除角色
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.warning('删除失败!')
        this.$message.success('删除成功！')
        // 重新获取角色列表
        this.getRolesList()
      } else {
        this.$message.info('已取消删除！')
      }
    },
    // 添加角色
    async addRoles() {
      const { data: res } = await this.$http.post('roles', this.addFormInfo)
      console.log(res)
      // if (res.meta.status !== 200) return this.$message.error('添加角色失败！')
      // 重新获取角色列表
      this.getRolesList()
      this.$message.success('添加角色成功！')
      this.addRoledialogVisible = false
    },
    // 删除角色权限
    async deleteRight(role, rightId) {
    // 删除前确认
      const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => { return err })
      if (result !== 'confirm') return this.$message.info('已取消删除!')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.warning('权限删除失败！')
      }
      this.$message.success('权限删除成功！')
      role.children = res.data
    },
    // 分配权限列表
    async setRightsListDialog(role) {
      // 发送请求获取权限列表数据
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败！')
      // 将获取到的权限列表传递给当前数据对象
      this.rightsList = res.data
      // 每次获取三级节点之前清空defKeys数组
      this.defKeys = []
      this.roleId = role.id
      console.log(this.roleId)
      // 获取三级节点id
      console.log(role)
      this.getLeafsId(role, this.defKeys)
      this.RightsListDialogVisible = true
    },
    // 使用递归获取三级权限id
    getLeafsId(node, arr) {
      // 如果没有children属性，则是三级节点
      if (!node.children) return arr.push(node.id)
      node.children.forEach(item => { this.getLeafsId(item, arr) })
    },
    // 给指定角色分配权限
    async authorityAssignment() {
      // 获取选中的叶子结点和半选中的节点的id值
      const leafsId = [
        this.$refs.treeRef.getCheckedKeys() + ',' + this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // 将数组转化为字符串join
      var idList = leafsId.join('')
      // 发送请求，分配权限
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idList })
      if (res.meta.status !== 200) return this.$message.error('权限配分配失败！')
      this.$message.success('权限分配成功！')
      // 刷新角色权限列表
      this.getRolesList()
      this.RightsListDialogVisible = false
    }
  }
}

</script>
<style lang="less" scoped>
.addRole {
  margin-bottom: 15px;
}
.el-tag {
  margin: 10px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bt {
  border-bottom: 1px solid #eee;
}
.veticalCenter {
  display: flex;
  align-items: center;
}
</style>
